package com.example.springBoot.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.springBoot.common.BaseController;
import com.example.springBoot.dao.ArticleTypeDao;
import com.example.springBoot.domain.ArticleType;

@Controller
public class ArticleTypeController extends BaseController {

	@Autowired
	private ArticleTypeDao articleTypeDao;

	@SuppressWarnings("null")
	@RequestMapping("/admin/findallarticletype")
	public String findallarticletype(Map<String, Object> map,
			@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Page<ArticleType> list = articleTypeDao.findAll(pageable);
		if (list != null || list.getSize() > 0) {
			map.put("list", list);
		}
		return "admin/articletype/list";
	}

	@RequestMapping("/admin/addarticleType")
	public String addarticletype(ArticleType articleType) {
		articleType = new ArticleType();
		return "admin/articletype/add";
	}

	@RequestMapping("/admin/savearticletype")
	public String savearticletype(ArticleType articleType) {
		if (articleType.getId() == null) {
			ArticleType sqlarticleType = new ArticleType();
			sqlarticleType.setTypeName(articleType.getTypeName());
			sqlarticleType.setTypeStatus(1);
			articleTypeDao.save(sqlarticleType);
		} else {
			ArticleType sqlarticleType = articleTypeDao.findById(articleType.getId());
			sqlarticleType.setTypeName(articleType.getTypeName());
			articleTypeDao.save(sqlarticleType);
		}
		return "redirect:/admin/findallarticletype";
	}

	@RequestMapping("/admin/updatearticletype/{id}")
	public String updatearticletype(@PathVariable Long id, Map<String, Object> map) {
		ArticleType articleType = articleTypeDao.findById(id);
		if (articleType == null) {
			return "redirect:/404";
		} else {
			map.put("articleType", articleType);
			return "admin/articletype/update";
		}
	}

	@RequestMapping("/admin/updatestatus/{id}")
	public String updatestatus(@PathVariable Long id) {
		if (id == null) {
			return "redirect:/404";
		}
		ArticleType articleType = articleTypeDao.findById(id);
		articleType.setTypeStatus((articleType.getTypeStatus() == 1) ? 2 : 1);
		articleTypeDao.save(articleType);
		return "redirect:/admin/findallarticletype";
	}

}
